<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">

<script>
    (function(){
        if(''){
            if (prompt('请输入文章密码') !== ''){
                alert('密码错误！');
                history.back();
            }
        }
    })();
</script>








<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.ico.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.ico.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.ico.png?v=5.1.4">


  <link rel="mask-icon" href="/images/favicon.ico.png?v=5.1.4" color="#222">





  <meta name="keywords" content="技术总结,Nginx," />





  <link rel="alternate" href="/atom.xml" title="Jacknolfskin" type="application/atom+xml" />






<meta name="description" content="定义Nginx运行的用户和用户组1user www www; nginx进程数，建议设置为等于CPU总核心数。1worker_processes 8; 配置文件正确性测试1./nginx -t">
<meta name="keywords" content="技术总结,Nginx">
<meta property="og:type" content="article">
<meta property="og:title" content="Nginx配置详解">
<meta property="og:url" content="https://www.jacknolfskin.top/技术总结/Nginx配置详解.html">
<meta property="og:site_name" content="Jacknolfskin">
<meta property="og:description" content="定义Nginx运行的用户和用户组1user www www; nginx进程数，建议设置为等于CPU总核心数。1worker_processes 8; 配置文件正确性测试1./nginx -t">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-03-08T01:19:10.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Nginx配置详解">
<meta name="twitter:description" content="定义Nginx运行的用户和用户组1user www www; nginx进程数，建议设置为等于CPU总核心数。1worker_processes 8; 配置文件正确性测试1./nginx -t">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.jacknolfskin.top/技术总结/Nginx配置详解.html"/>





  <title>Nginx配置详解 | Jacknolfskin</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/Jacknolfskin"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Jacknolfskin</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.jacknolfskin.top/技术总结/Nginx配置详解.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Jack Hu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Jacknolfskin">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Nginx配置详解</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-06-13T11:27:01+08:00">
                2018-06-13
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-03-08T09:19:10+08:00">
                2018-03-08
              </time>
            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Nginx/" itemprop="url" rel="index">
                    <span itemprop="name">Nginx</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/技术总结/Nginx配置详解.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/技术总结/Nginx配置详解.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/技术总结/Nginx配置详解.html" class="leancloud_visitors" data-flag-title="Nginx配置详解">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,210 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="定义Nginx运行的用户和用户组"><a href="#定义Nginx运行的用户和用户组" class="headerlink" title="定义Nginx运行的用户和用户组"></a>定义Nginx运行的用户和用户组</h4><figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">user</span> <span class="title">www</span> www;</span><br></pre></td></tr></table></figure>
<h4 id="nginx进程数，建议设置为等于CPU总核心数。"><a href="#nginx进程数，建议设置为等于CPU总核心数。" class="headerlink" title="nginx进程数，建议设置为等于CPU总核心数。"></a>nginx进程数，建议设置为等于CPU总核心数。</h4><figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker_processes <span class="number">8</span><span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h4 id="配置文件正确性测试"><a href="#配置文件正确性测试" class="headerlink" title="配置文件正确性测试"></a>配置文件正确性测试</h4><figure class="highlight excel"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">./nginx -<span class="built_in">t</span></span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h4 id="全局错误日志定义类型，-debug-info-notice-warn-error-crit"><a href="#全局错误日志定义类型，-debug-info-notice-warn-error-crit" class="headerlink" title="全局错误日志定义类型，[ debug | info | notice | warn | error | crit ]"></a>全局错误日志定义类型，[ debug | info | notice | warn | error | crit ]</h4><figure class="highlight maxima"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">error_log /<span class="built_in">var</span>/<span class="built_in">log</span>/nginx/<span class="built_in">error</span>.<span class="built_in">log</span> info;</span><br></pre></td></tr></table></figure>
<h4 id="进程文件"><a href="#进程文件" class="headerlink" title="进程文件"></a>进程文件</h4><figure class="highlight dockerfile"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">pid /var/<span class="keyword">run</span><span class="bash">/nginx.pid;</span></span><br></pre></td></tr></table></figure>
<h4 id="一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit-n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit-n的值保持一致。"><a href="#一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit-n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit-n的值保持一致。" class="headerlink" title="一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit -n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit -n的值保持一致。"></a>一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit -n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit -n的值保持一致。</h4><figure class="highlight abnf"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">worker_rlimit_nofile <span class="number">65535</span><span class="comment">;</span></span><br></pre></td></tr></table></figure>
<h4 id="设定http服务器"><a href="#设定http服务器" class="headerlink" title="设定http服务器"></a>设定http服务器</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">http</span><br><span class="line">&#123;</span><br><span class="line"><span class="attribute">include</span> mime.types; <span class="comment">#文件扩展名与文件类型映射表</span></span><br><span class="line"><span class="attribute">default_type</span> application/octet-stream; <span class="comment">#默认文件类型</span></span><br></pre></td></tr></table></figure>
<h4 id="charset-utf-8-默认编码"><a href="#charset-utf-8-默认编码" class="headerlink" title="charset utf-8; #默认编码"></a>charset utf-8; #默认编码</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">server_names_hash_bucket_size</span> <span class="number">128</span>; <span class="comment">#服务器名字的hash表大小</span></span><br><span class="line"><span class="attribute">client_header_buffer_size</span> <span class="number">32k</span>; <span class="comment">#上传文件大小限制</span></span><br><span class="line"><span class="attribute">large_client_header_buffers</span> <span class="number">4</span> <span class="number">64k</span>; <span class="comment">#设定请求缓</span></span><br><span class="line"><span class="attribute">client_max_body_size</span> <span class="number">8m</span>; <span class="comment">#设定请求缓</span></span><br><span class="line"><span class="attribute">sendfile</span> <span class="literal">on</span>; <span class="comment">#开启高效文件传输模式，sendfile指令指定nginx是否调用sendfile函数来输出文件，对于普通应用设为 on，如果用来进行下载等应用磁盘IO重负载应用，可设置为off，以平衡磁盘与网络I/O处理速度，降低系统的负载。注意：如果图片显示不正常把这个改成off。</span></span><br><span class="line"><span class="attribute">autoindex</span> <span class="literal">on</span>; <span class="comment">#开启目录列表访问，合适下载服务器，默认关闭。</span></span><br><span class="line"><span class="attribute">tcp_nopush</span> <span class="literal">on</span>; <span class="comment">#防止网络阻塞</span></span><br><span class="line"><span class="attribute">tcp_nodelay</span> <span class="literal">on</span>; <span class="comment">#防止网络阻塞</span></span><br><span class="line"><span class="attribute">keepalive_timeout</span> <span class="number">120</span>; <span class="comment">#长连接超时时间，单位是秒</span></span><br></pre></td></tr></table></figure>
<h4 id="FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。"><a href="#FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。" class="headerlink" title="FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。"></a>FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。</h4><figure class="highlight lsl"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">fastcgi_connect_timeout <span class="number">300</span>;</span><br><span class="line">fastcgi_send_timeout <span class="number">300</span>;</span><br><span class="line">fastcgi_read_timeout <span class="number">300</span>;</span><br><span class="line">fastcgi_buffer_size <span class="number">64</span>k;</span><br><span class="line">fastcgi_buffers <span class="number">4</span> <span class="number">64</span>k;</span><br><span class="line">fastcgi_busy_buffers_size <span class="number">128</span>k;</span><br><span class="line">fastcgi_temp_file_write_size <span class="number">128</span>k;</span><br></pre></td></tr></table></figure>
<h4 id="gzip模块设置"><a href="#gzip模块设置" class="headerlink" title="gzip模块设置"></a>gzip模块设置</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">gzip</span> <span class="literal">on</span>; <span class="comment">#开启gzip压缩输出</span></span><br><span class="line"><span class="attribute">gzip_min_length</span> <span class="number">1k</span>; <span class="comment">#最小压缩文件大小</span></span><br><span class="line"><span class="attribute">gzip_buffers</span> <span class="number">4</span> <span class="number">16k</span>; <span class="comment">#压缩缓冲区</span></span><br><span class="line"><span class="attribute">gzip_http_version</span> <span class="number">1</span>.<span class="number">0</span>; <span class="comment">#压缩版本（默认1.1，前端如果是squid2.5请使用1.0）</span></span><br><span class="line"><span class="attribute">gzip_comp_level</span> <span class="number">2</span>; <span class="comment">#压缩等级</span></span><br><span class="line"><span class="attribute">gzip_types</span> text/plain application/x-javascript text/css application/xml;</span><br></pre></td></tr></table></figure>
<h4 id="压缩类型，默认就已经包含text-html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。"><a href="#压缩类型，默认就已经包含text-html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。" class="headerlink" title="压缩类型，默认就已经包含text/html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。"></a>压缩类型，默认就已经包含text/html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。</h4><figure class="highlight applescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">gzip_vary <span class="keyword">on</span>;</span><br></pre></td></tr></table></figure>
<h4 id="负载均衡"><a href="#负载均衡" class="headerlink" title="负载均衡"></a>负载均衡</h4><figure class="highlight routeros"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">upstream blog.ha97.com &#123;</span><br><span class="line"><span class="comment">#upstream的负载均衡，weight是权重，可以根据机器配置定义权重。weigth参数表示权值，权值越高被分配到的几率越大。</span></span><br><span class="line">server 192.168.80.121:80 <span class="attribute">weight</span>=3;</span><br><span class="line">server 192.168.80.122:80 <span class="attribute">weight</span>=2;</span><br><span class="line">server 192.168.80.123:80 <span class="attribute">weight</span>=3;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="虚拟主机的配置"><a href="#虚拟主机的配置" class="headerlink" title="虚拟主机的配置"></a>虚拟主机的配置</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">server</span><br><span class="line">&#123;</span><br><span class="line"><span class="comment">#监听端口</span></span><br><span class="line"><span class="attribute">listen</span> <span class="number">80</span>;</span><br><span class="line"><span class="comment">#域名可以有多个，用空格隔开</span></span><br><span class="line"><span class="attribute">server_name</span> www.ha97.com ha97.com;</span><br><span class="line"><span class="attribute">index</span> index.html index.htm index.php;</span><br><span class="line"><span class="attribute">root</span> /data/www/ha97;</span><br><span class="line"><span class="attribute">location</span> <span class="regexp">~ .*.(php|php5)?$</span></span><br><span class="line"><span class="regexp"></span>&#123;</span><br><span class="line"><span class="attribute">fastcgi_pass</span> <span class="number">127.0.0.1:9000</span>;</span><br><span class="line"><span class="attribute">fastcgi_index</span> index.php;</span><br><span class="line"><span class="attribute">include</span> fastcgi.conf;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="图片缓存时间设置"><a href="#图片缓存时间设置" class="headerlink" title="图片缓存时间设置"></a>图片缓存时间设置</h4><figure class="highlight coq"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">location ~ .*.(gif|<span class="type">jpg</span>|<span class="type">jpeg</span>|<span class="type">png</span>|<span class="type">bmp</span>|<span class="type">swf</span>)$</span><br><span class="line">&#123;</span><br><span class="line">expires <span class="number">10</span>d;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="JS和CSS缓存时间设置"><a href="#JS和CSS缓存时间设置" class="headerlink" title="JS和CSS缓存时间设置"></a>JS和CSS缓存时间设置</h4><figure class="highlight crmsh"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">location</span> <span class="title">~ .*.(js</span>|css)?$</span><br><span class="line">&#123;</span><br><span class="line">expires <span class="number">1h</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h4 id="日志格式设定"><a href="#日志格式设定" class="headerlink" title="日志格式设定"></a>日志格式设定</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">log_format</span> access <span class="string">'<span class="variable">$remote_addr</span> - <span class="variable">$remote_user</span> [<span class="variable">$time_local</span>] "<span class="variable">$request</span>" '</span></span><br><span class="line"><span class="string">'<span class="variable">$status</span> <span class="variable">$body_bytes_sent</span> "<span class="variable">$http_referer</span>" '</span></span><br><span class="line"><span class="string">'"<span class="variable">$http_user_agent</span>" <span class="variable">$http_x_forwarded_for</span>'</span>;</span><br></pre></td></tr></table></figure>
<h4 id="定义本虚拟主机的访问日志"><a href="#定义本虚拟主机的访问日志" class="headerlink" title="定义本虚拟主机的访问日志"></a>定义本虚拟主机的访问日志</h4><figure class="highlight fortran"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">access_log /var/<span class="built_in">log</span>/nginx/ha97access.<span class="built_in">log</span> <span class="keyword">access</span>;</span><br></pre></td></tr></table></figure>
<h4 id="对-“-“-启用反向代理"><a href="#对-“-“-启用反向代理" class="headerlink" title="对 “/“ 启用反向代理"></a>对 “/“ 启用反向代理</h4><figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="attribute">location</span> / &#123;</span><br><span class="line"><span class="attribute">proxy_pass</span> http://127.0.0.1:88;</span><br><span class="line"><span class="attribute">proxy_redirect</span> <span class="literal">off</span>;</span><br><span class="line"><span class="attribute">proxy_set_header</span> X-Real-IP <span class="variable">$remote_addr</span>;</span><br><span class="line"><span class="comment">#后端的Web服务器可以通过X-Forwarded-For获取用户真实IP</span></span><br><span class="line"><span class="attribute">proxy_set_header</span> X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</span><br><span class="line"><span class="comment">#以下是一些反向代理的配置，可选。</span></span><br><span class="line"><span class="attribute">proxy_set_header</span> Host <span class="variable">$host</span>;</span><br><span class="line"><span class="attribute">client_max_body_size</span> <span class="number">10m</span>; <span class="comment">#允许客户端请求的最大单文件字节数</span></span><br><span class="line"><span class="attribute">client_body_buffer_size</span> <span class="number">128k</span>; <span class="comment">#缓冲区代理缓冲用户端请求的最大字节数，</span></span><br><span class="line"><span class="attribute">proxy_connect_timeout</span> <span class="number">90</span>; <span class="comment">#nginx跟后端服务器连接超时时间(代理连接超时)</span></span><br><span class="line"><span class="attribute">proxy_send_timeout</span> <span class="number">90</span>; <span class="comment">#后端服务器数据回传时间(代理发送超时)</span></span><br><span class="line"><span class="attribute">proxy_read_timeout</span> <span class="number">90</span>; <span class="comment">#连接成功后，后端服务器响应时间(代理接收超时)</span></span><br><span class="line"><span class="attribute">proxy_buffer_size</span> <span class="number">4k</span>; <span class="comment">#设置代理服务器（nginx）保存用户头信息的缓冲区大小</span></span><br><span class="line"><span class="attribute">proxy_buffers</span> <span class="number">4</span> <span class="number">32k</span>; <span class="comment">#proxy_buffers缓冲区，网页平均在32k以下的设置</span></span><br><span class="line"><span class="attribute">proxy_busy_buffers_size</span> <span class="number">64k</span>; <span class="comment">#高负荷下缓冲大小（proxy_buffers*2）</span></span><br><span class="line"><span class="attribute">proxy_temp_file_write_size</span> <span class="number">64k</span>;</span><br></pre></td></tr></table></figure>
<h4 id="设定缓存文件夹大小，大于这个值，将从upstream服务器传"><a href="#设定缓存文件夹大小，大于这个值，将从upstream服务器传" class="headerlink" title="设定缓存文件夹大小，大于这个值，将从upstream服务器传"></a>设定缓存文件夹大小，大于这个值，将从upstream服务器传</h4><p>}</p>
<figure class="highlight nginx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">#设定查看Nginx状态的地址</span></span><br><span class="line"><span class="attribute">location</span> /NginxStatus &#123;</span><br><span class="line"><span class="attribute">stub_status</span> <span class="literal">on</span>;</span><br><span class="line"><span class="attribute">access_log</span> <span class="literal">on</span>;</span><br><span class="line"><span class="attribute">auth_basic</span> <span class="string">"NginxStatus"</span>;</span><br><span class="line"><span class="attribute">auth_basic_user_file</span> conf/htpasswd;</span><br><span class="line"><span class="comment">#htpasswd文件的内容可以用apache提供的htpasswd工具来产生。</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">#本地动静分离反向代理配置</span></span><br><span class="line"><span class="comment">#所有jsp的页面均交由tomcat或resin处理</span></span><br><span class="line"><span class="attribute">location</span> <span class="regexp">~ .(jsp|jspx|do)?$</span> &#123;</span><br><span class="line"><span class="attribute">proxy_set_header</span> Host <span class="variable">$host</span>;</span><br><span class="line"><span class="attribute">proxy_set_header</span> X-Real-IP <span class="variable">$remote_addr</span>;</span><br><span class="line"><span class="attribute">proxy_set_header</span> X-Forwarded-For <span class="variable">$proxy_add_x_forwarded_for</span>;</span><br><span class="line"><span class="attribute">proxy_pass</span> http://127.0.0.1:8080;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">#所有静态文件由nginx直接读取不经过tomcat或resin</span></span><br><span class="line"><span class="attribute">location</span> <span class="regexp">~ .*.(htm|html|gif|jpg|jpeg|png|bmp|swf|ioc|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$</span></span><br><span class="line"><span class="regexp"></span>&#123; <span class="attribute">expires</span> <span class="number">15d</span>; &#125;</span><br><span class="line"><span class="attribute">location</span> <span class="regexp">~ .*.(js|css)?$</span></span><br><span class="line"><span class="regexp"></span>&#123; <span class="attribute">expires</span> <span class="number">1h</span>; &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>坚持原创技术分享，您的支持将鼓励我继续创作！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="Jack Hu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    <div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
    
</div>
  
    </div>

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    Jack Hu
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://www.jacknolfskin.top/技术总结/Nginx配置详解.html" title="Nginx配置详解">https://www.jacknolfskin.top/技术总结/Nginx配置详解.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/技术总结/" rel="tag"><i class="fa fa-tag"></i> 技术总结</a>
          
            <a href="/tags/Nginx/" rel="tag"><i class="fa fa-tag"></i> Nginx</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/博客建设/使用Hexo+NextT搭建博客.html" rel="next" title="使用 Hexo + NexT 搭建静态博客">
                <i class="fa fa-chevron-left"></i> 使用 Hexo + NexT 搭建静态博客
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/技术总结/守护线程.html" rel="prev" title="关于守护线程">
                关于守护线程 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "1",
        "bdMiniList": false,
        "bdPic": ""
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      },
      "slide": {
        "bdImg": "5",
        "bdPos": "left",
        "bdTop": "100"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="Jack Hu" />
            
              <p class="site-author-name" itemprop="name">Jack Hu</p>
              <p class="site-description motion-element" itemprop="description">不以物喜，不以己悲</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">15</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">10</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">21</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://www.jianshu.com/u/543bda7a326b" target="_blank" title="简书">
                      
                        <i class="fa fa-fw fa-book"></i>简书</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.zhihu.com/people/hu-fei-80-33-93/activities" target="_blank" title="知乎">
                      
                        <i class="fa fa-fw fa-leanpub"></i>知乎</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="" title="1352490133@qq.com" target="_blank">1352490133@qq.com</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#定义Nginx运行的用户和用户组"><span class="nav-number">1.</span> <span class="nav-text">定义Nginx运行的用户和用户组</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#nginx进程数，建议设置为等于CPU总核心数。"><span class="nav-number">2.</span> <span class="nav-text">nginx进程数，建议设置为等于CPU总核心数。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#配置文件正确性测试"><span class="nav-number">3.</span> <span class="nav-text">配置文件正确性测试</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#全局错误日志定义类型，-debug-info-notice-warn-error-crit"><span class="nav-number">4.</span> <span class="nav-text">全局错误日志定义类型，[ debug | info | notice | warn | error | crit ]</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#进程文件"><span class="nav-number">5.</span> <span class="nav-text">进程文件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit-n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit-n的值保持一致。"><span class="nav-number">6.</span> <span class="nav-text">一个nginx进程打开的最多文件描述符数目，理论值应该是最多打开文件数（系统的值ulimit -n）与nginx进程数相除，但是nginx分配请求并不均匀，所以建议与ulimit -n的值保持一致。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设定http服务器"><span class="nav-number">7.</span> <span class="nav-text">设定http服务器</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#charset-utf-8-默认编码"><span class="nav-number">8.</span> <span class="nav-text">charset utf-8; #默认编码</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。"><span class="nav-number">9.</span> <span class="nav-text">FastCGI相关参数是为了改善网站的性能：减少资源占用，提高访问速度。下面参数看字面意思都能理解。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#gzip模块设置"><span class="nav-number">10.</span> <span class="nav-text">gzip模块设置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#压缩类型，默认就已经包含text-html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。"><span class="nav-number">11.</span> <span class="nav-text">压缩类型，默认就已经包含text/html，所以下面就不用再写了，写上去也不会有问题，但是会有一个warn。</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#负载均衡"><span class="nav-number">12.</span> <span class="nav-text">负载均衡</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#虚拟主机的配置"><span class="nav-number">13.</span> <span class="nav-text">虚拟主机的配置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#图片缓存时间设置"><span class="nav-number">14.</span> <span class="nav-text">图片缓存时间设置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#JS和CSS缓存时间设置"><span class="nav-number">15.</span> <span class="nav-text">JS和CSS缓存时间设置</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日志格式设定"><span class="nav-number">16.</span> <span class="nav-text">日志格式设定</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#定义本虚拟主机的访问日志"><span class="nav-number">17.</span> <span class="nav-text">定义本虚拟主机的访问日志</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#对-“-“-启用反向代理"><span class="nav-number">18.</span> <span class="nav-text">对 “/“ 启用反向代理</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#设定缓存文件夹大小，大于这个值，将从upstream服务器传"><span class="nav-number">19.</span> <span class="nav-text">设定缓存文件夹大小，大于这个值，将从upstream服务器传</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<!-- time -->
  <div id="show-time">
    <i class="fa fa-clock-o"></i>
    <span id="span_dt_dt"></span>
  </div>

<div class="copyright">

&copy; Thu Jan 25 2018 08:00:00 GMT+0800 (GMT+08:00) &mdash; 
<span itemprop="copyrightYear">2018</span>
<span class="with-love">
    <i class="fa fa-user"></i>
  </span>
<span class="author" itemprop="copyrightHolder">Jack Hu</span>

  
</div>

<div class="powered-by">
<i class="fa fa-anchor"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div>


  <span class="post-meta-divider">|</span>


<div class="powered-by">
<i class="fa fa-eye"></i>
<span id="busuanzi_container_site_pv">
  本站访问量:<span id="busuanzi_value_site_pv"></span>
</span>
</div>





  <span class="post-meta-divider">|</span>


<div class="theme-info">
<i class="fa fa-file-text-o"></i>
  <div class="powered-by"></div>
  <span class="post-count">全站共18.9k字</span>
</div>

  
  <span class="post-meta-divider">|</span>
  <span>Hosted by <a href="https://pages.coding.me" >Coding Pages</a></span>
  

  <script>
      function show_date_time() {
        window.setTimeout("show_date_time()", 1000);
        BirthDay = new Date("11/24/2017 09:00:00");
        today = new Date();
        //总时间
        timeold = (today.getTime() - BirthDay.getTime());
        sectimeold = timeold / 1000
        secondsold = Math.floor(sectimeold);
        msPerDay = 24 * 60 * 60 * 1000
        e_daysold = timeold / msPerDay
        daysold = Math.floor(e_daysold);
        e_hrsold = (e_daysold - daysold) * 24;
        hrsold = Math.floor(e_hrsold);
        e_minsold = (e_hrsold - hrsold) * 60;
        minsold = Math.floor((e_hrsold - hrsold) * 60);
        seconds = Math.floor((e_minsold - minsold) * 60);
        span_dt_dt.innerHTML = "本站已运行 " + daysold + " 天 " + hrsold + " 小时 " + minsold + " 分 " + seconds + " 秒";
    }
        show_date_time();
  </script>

        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  




  
  









  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three.min.js"></script>
  

  
  
    <script type="text/javascript" src="/lib/three/three-waves.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: true,
        appId: 'NcINm9QV7WmUEp6IS61SYrme-gzGzoHsz',
        appKey: 'mpyaCm2LnY6gLGKsS5BK3uMd',
        placeholder: '留下你的评论',
        avatar:'',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NcINm9QV7WmUEp6IS61SYrme-gzGzoHsz", "mpyaCm2LnY6gLGKsS5BK3uMd");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
    
  </script>

  

  

  

  

</body>
</html>
